package com.meida.module.bus.provider.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.google.common.collect.Lists;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.module.bus.client.entity.BusProject;
import com.meida.module.bus.client.entity.BusProjectFile;
import com.meida.module.bus.client.entity.srmapi.srmtopms.SrmSyncFileResDetail;
import com.meida.module.bus.client.entity.srmapi.srmtopms.SrmSyncFileResSub;
import com.meida.module.bus.provider.api.service.SyncSrmService;
import com.meida.module.bus.provider.mapper.BusProjectFileMapper;
import com.meida.module.bus.provider.service.BusProjectFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 上传文件接口实现类
 * @Author: ccc
 **/
@Service
@Transactional(rollbackFor = Exception.class)
@DS("master")
public class BusProjectFileServiceImpl extends BaseServiceImpl<BusProjectFileMapper, BusProjectFile> implements BusProjectFileService {
    @Autowired
    private SyncSrmService syncSrmService;

	@Override
	public ResultBody upFileService(String filePath, String nameTypePath, MultipartFile[] files, Long projectId, String uniqueFlag) {
		try {
		    List<BusProjectFile> list = Lists.newArrayList();
		    String fileName = null;
		    for(MultipartFile file: files) {
		        //获取文件名称
                fileName = file.getOriginalFilename();
                File file1 = new File(filePath);
                //创建目录
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                byte[] bytes = file.getBytes();
                String url = filePath + fileName;
                Path path = Paths.get(url);
                //写入文件
                Files.write(path, bytes);
                //写入记录
                BusProjectFile projectFile = new BusProjectFile();
                projectFile.setFileName(fileName);
                projectFile.setProjectId(projectId);
                projectFile.setUserId(OpenHelper.getUserId());
                projectFile.setUserName(OpenHelper.getUserName());
                projectFile.setUniqueFlag(uniqueFlag);
                projectFile.setCreateTime(new Date());
                projectFile.setFilePath(nameTypePath+fileName);
                projectFile.setSyncFlag("N");
                projectFile.setProjectFileId(UUID.randomUUID().toString().trim().replaceAll("-", ""));
                list.add(projectFile);
            }
		    //批量插入记录
            saveBatch(list);
			return ResultBody.ok(uniqueFlag);
		} catch (IOException e) {
			e.printStackTrace();
			return ResultBody.failed(e.getMessage());
		}
	}
	
	@Override
	public void download(String filePath, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(filePath);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            // String ext = filename.substring(filename.lastIndexOf(".") +
            // 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition",
                "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
	}

    /**
     * 更新附件对应的申请记录ID
     * @param uniqueFlag
     * @param purchaseId
     */
    @Override
    public void updatePurchaseId(String uniqueFlag, Long purchaseId) {
        CriteriaUpdate<BusProjectFile> cu = new CriteriaUpdate();
        cu.eq("uniqueFlag", uniqueFlag);
        cu.set("purchaseId", purchaseId);
        update(cu);
        //同步SRM
        syncSrm(purchaseId);
    }

    @Async("asyncServiceExecutor")
    public void syncSrm(Long purchaseId) {
        try {
            syncSrmService.syncMaterialApplicationFile(purchaseId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新附件对应的同步信息
     * @param srmSyncFileResSub
     */
    @Override
    public void updateSyncFileState(SrmSyncFileResSub srmSyncFileResSub) {
        if(srmSyncFileResSub != null && !CollectionUtils.isEmpty(srmSyncFileResSub.getDetails())) {
            CriteriaUpdate<BusProjectFile> cu = new CriteriaUpdate();
            cu.eq("purchaseId", srmSyncFileResSub.getPurchaseId());
            //获取本次记录的附件记录
            List<BusProjectFile> projectFiles = list(cu);
            if(!CollectionUtils.isEmpty(projectFiles)) {
                for(BusProjectFile source: projectFiles) {
                    //设置附件组ID
                    source.setFileGroupId(srmSyncFileResSub.getFileGroupId());
                    source.setSyncFlag(getResFileState(srmSyncFileResSub.getDetails(), source.getProjectFileId()));
                }
                saveOrUpdateBatch(projectFiles);
            }
        }
    }

    /**
     * 获取某次申请记录的SRM附件组ID
     * @param purchaseId
     * @return
     */
    @Override
    public String getFileGroupIdByPurchaseId(Long purchaseId) {
        if(purchaseId != null) {
            CriteriaQuery<BusProjectFile> cu = new CriteriaQuery(BusProjectFile.class);
            cu.eq("purchaseId", purchaseId);
            cu.isNotNull("fileGroupId");
            //查找本次申请的附件信息
            List<BusProjectFile> projectFiles = list(cu);
            return CollectionUtils.isEmpty(projectFiles)?null:projectFiles.get(0).getFileGroupId();
        }
        return null;
    }

    /**
     * 获取接口返回的附件同步结果
     * @param resDetails
     * @param projectFileId
     * @return
     */
    public String getResFileState(List<SrmSyncFileResDetail> resDetails, String projectFileId) {
        for(SrmSyncFileResDetail item: resDetails) {
            if(projectFileId.equals(item.getProjectFileId())) {
                return item.getSyncFlag();
            }
        }
        return null;
    }

}
